<?php

namespace yifang\db;

class Fetch
{
    /**
     * 查询对象
     * @var Query
     */
    protected $query;

    /**
     * Connection对象
     * @var Connection
     */
    protected $connection;

    /**
     * Builder对象
     * @var Builder
     */
    protected $builder;

    /**
     * 创建一个查询SQL获取对象
     *
     * @param  Query    $query      查询对象
     */
    public function __construct(Query $query)
    {
        $this->query      = $query;
        $this->connection = $query->getConnection();
        $this->builder    = $this->connection->getBuilder();
    }

    /**
     * 查找记录 返回SQL
     * @access public
     * @param  mixed $data
     * @return string
     */
    public function select($data = null)
    {
        $this->query->parseOptions();
        if (!is_null($data)) {
            // 主键条件分析
            $this->query->parsePkWhere($data);
        }
        // 生成查询SQL
        $sql = $this->builder->select($this->query);
        return $this->fetch($sql);
    }

    /**
     * 查找单条记录 返回SQL语句
     * @access public
     * @param  mixed $data
     * @return string
     */
    public function find($data = null)
    {
        $this->query->parseOptions();
        if (!is_null($data)) {
            // AR模式分析主键条件
            $this->query->parsePkWhere($data);
        }
        // 生成查询SQL
        $sql = $this->builder->select($this->query, true);
        // 获取实际执行的SQL语句
        return $this->fetch($sql);
    }

    /**
     * 获取实际的SQL语句
     * @access public
     * @param  string $sql
     * @return string
     */
    public function fetch($sql)
    {
        $bind = $this->query->getBind();
        return $this->connection->getRealSql($sql, $bind);
    }
}